package systempen.cmanager;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import systempen.cmanager.DialogAddCost.IRefreshList;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ListActivity;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.view.LayoutInflater;

public class CostTypes extends ListActivity {
	ListActivity thisclass;
	static final private int CATEGORY_DETAIL = 1;
	public OnItemClickListener kl;
	public View arg;
	public ListView lv;
	public String sentCostCode;
	public View poslati;
	public View poslati2;
	public View poslati3;
	public String cost;
	public String Level;
	public Button bPath;
	private String selectedWord = null;
    public String contextID; //context na koji si kliknuo
    public String defaultCustomDialog;
    public Button butInsertIn;
    public String fromDate;
    public String toDate;
	@Override
	public void onCreate(Bundle icicle){
		super.onCreate(icicle);
		ThemePicker.onActivityCreateSetTheme(this);
		try{
			String defaultPeriod = util.GetDefaultPeriod(getApplicationContext());
	        if (defaultPeriod.equals("THISMONTH")){
	        	fromDate = util.GetThisMonthPeriodDB().a.toString();
	        	toDate = util.GetThisMonthPeriodDB().b.toString();
	        } else
	        if (defaultPeriod.equals("LASTMONTH")){
	        	fromDate = util.GetLastMonthPeriodDB().a.toString();
	        	toDate = util.GetLastMonthPeriodDB().b.toString();
	        } else 
	        if (defaultPeriod.equals("TODAY")){
	        	fromDate = util.GetTodayPeriodDB().a.toString();
	        	toDate = util.GetTodayPeriodDB().b.toString();
	        } else
	        if (defaultPeriod.equals("ALLTIME")){
	        	fromDate = "1900-01-01";
	        	toDate = "3000-01-01";
	        } else
	        if (defaultPeriod.equals("THISWEEK")){
	        	fromDate = util.GetThisWeekPeriodDB().a.toString();
	        	toDate = util.GetThisWeekPeriodDB().b.toString();
	        }
	        else{
	        	fromDate = "1900-01-01"; //za nedaj boze
	        	toDate = "3000-01-01";
	        }
	        
	        setContentView(R.layout.costtypes);
			Bundle bun = getIntent().getExtras();
			thisclass = this;
			cost = bun.getString("Cost");
			Level = bun.getString("Level");
			bPath = (Button)findViewById(R.id.ButPath);
			bPath.setText(getPathOfLevel(Level));
			butInsertIn = (Button)findViewById(R.id.ButInsertIn);
			butInsertIn.setText("Insert in:"+util.getLevelName(Level, getApplicationContext()));
			if(bPath.getText().equals(""))
			{bPath.setText("Root");}
			//ArrayList<String> results = new ArrayList<String>();
			//thisclass = this;
			lv = getListView();
			registerForContextMenu(lv);
			attachListListener();
			lv.setOnItemClickListener(kl);
			fillList();
		}//od try
		catch(Exception ex) 
		{
			Toast.makeText(this,"Costtypes: FFS: "+ex.getMessage(), Toast.LENGTH_LONG).show();
		}
		
	}
	public String getPathOfLevel(String levelID){//trebalo mi je 4 sata za ovo, al sam izlapio... note to self: sledeci put iskopiraj, konju!
		String parent = util.parentLevelExists(levelID,this);
		if (parent!=""){//ako postoji parent daj ga ako ne onda to je to
			String povratni = getPathOfLevel(parent) +" > "+util.getLevelName(levelID,this);
			return povratni;
		}else{
			if (levelID.equals("0")){
				levelID = "Root";
			}
			return levelID;
		}
	}
	public void attachListListener(){
		kl = new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
				//if there are child costs than open them
				poslati = ((RelativeLayout) arg1).findViewById(R.id.ctcode);
				poslati2 = ((RelativeLayout) arg1).findViewById(R.id.ctcode);
				poslati3 = ((RelativeLayout) arg1).findViewById(R.id.ctgornji);
				String ttt = ((TextView)poslati3).getText().toString();  
				
				if (util.existsChildCost(((TextView)poslati).getText().toString(), getApplicationContext())==true)
				{
					//call your self with that parameter
					//startActivity(new Intent(this, CostTypes.class));
					Intent intent = new Intent(Intent.ACTION_VIEW);
					intent.setClassName(getApplicationContext(), CostTypes.class.getName());
					Bundle bun = new Bundle();
					bun.putString("Cost", cost.toString());
					bun.putString("Level", ((TextView)poslati).getText().toString());
					intent.putExtras(bun);
					startActivity(intent);
				}else{
					if  (ttt.equals("No types in database, add new type?")){
						//Dodaj nulti level
			        	DialogAddCost da = new DialogAddCost(thisclass, "0", new IRefreshList() {
							
							@Override
							public void onRefreshList() {
								lv.setAdapter(null);
								fillList();//refresh
							}
						});
			        	da.show();
					} else if (ttt.equals("Add new type")){//klikno je na onaj donji 
							DialogAddCost da = new DialogAddCost(thisclass, Level, new IRefreshList() {
							@Override
							public void onRefreshList() {//ovaj bolje da je nazvan after insert
								lv.setAdapter(null);
								fillList();//refresh
							}
						});
			        	da.show();
					} else //normal add
					askToInsert(arg1);
				}
			}
		};
	}

	@Override //pressed back button cya
	public boolean onKeyDown(int keyCode, KeyEvent event)  {
	    if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
	    		startActivity(new Intent(this, MainActivityTab.class)); 
	        return true;
	    }
	    return super.onKeyDown(keyCode, event);
	}
	
	public void fillList(){
		Cursor c;
		ArrayList<CostListItem> m_Devices = new ArrayList<CostListItem>();
        List<HashMap<String, String>> fillMaps = new ArrayList<HashMap<String, String>>();
        util u = new util();
		c = u.getCursor("select name as name, code as _id, code as code, orde from cost_type where parent ="+Level.toString()+" union all select 'Add new type', 1000, 1000,1000 order by orde",thisclass);
		c.moveToFirst();
		int i = c.getCount();
		if (i==0){
			c = null;
			util u2 = new util();
			c = u2.getCursor("select 'No types in database, add new type?' as _id, 'No types in database,' as _id2, 0 as _id3",thisclass);
		}
		if (c.getCount()>0){
		 if (c.moveToFirst()) { 
             CostListItem device;
			 do {
				 String numberOfSubrtpes = util.getSubtypes(c.getString(2).toString(),this);
				 if (numberOfSubrtpes  == null)
						 numberOfSubrtpes = "0";
				 String suma="";
				 suma = util.getCostSum(c.getString(2).toString(),fromDate,toDate,"", this);
				 if (c.getString(0).equals("Add new type")) //ako je poslednji red
					 suma = "";
				 String gornji  = c.getString(0);
				 Cursor c2;
				 util u3 = new util();
				 c2 = u3.getCursor("select whe from log where cost_code = "+c.getString(2).toString()+" order by whe desc limit 1", thisclass);
				 c2.moveToFirst();
				 String lastInsert="";
				 if (c2.getCount()>0){
					 lastInsert = c2.getString(0);
					 lastInsert = util.dbStringDateToViewStringDate(lastInsert,getApplicationContext());
					 lastInsert = "Last insert: "+lastInsert;
				 }else{
					 lastInsert = "";
				 }
				 c2.close();
				 u3.db.close();
				 String donji  = lastInsert;
				 String code  = c.getString(2);
				 String cifra = suma;
				 String opis = "";
                 if (util.existsChildCost(code, getApplicationContext())){
		            	opis = "Contains subtypes";
                 }
				 device = new CostListItem();// ListItemL(gornji,donji,code,cifra,opis,"","","");
				 device.setGornji(gornji);
				 device.setDonji(donji);
				 device.setCode(code);
				 device.setCifra(cifra);
				 device.setOpis(opis);
				 device.setType("");
				 device.setPath("");
				 device.setOpis2("");
				 m_Devices.add(device);
				 }while (c.moveToNext()); 
			 } 
		 }
		c.close();//upitno
		u.db.close();
		CostListAdapter lvAdapter =  new CostListAdapter(this, R.layout.costlist_row, m_Devices);
		this.setListAdapter(lvAdapter);
	}
	
	public void askToInsert(View arg1){
		arg = arg1;
		AlertDialog.Builder alt_bld = new AlertDialog.Builder(this);
		poslati = ((RelativeLayout) arg1).findViewById(R.id.ctdonji);
		poslati2 = ((RelativeLayout) arg1).findViewById(R.id.ctcode);
		alt_bld.setMessage("Attach Cost to Type: "+((TextView)poslati).getText().toString());
		alt_bld.setCancelable(false);
		alt_bld.setPositiveButton("Yes", new OnClickListener(){
			public void onClick(DialogInterface dialog, int id){
				CostInsert();
			};
			/*ovaj koncept za mene je los ali tako su ga ljudi napravili
			 * znaci event se realizuje kroz implementaciju nekog tamo striktno propisanog interfejsa
			 * i jedina veza sa ostatkom koda(objektima) je kroz parametar koji se prosledjuje interfejsu 
			 * DialogInterface dialog - ali ovo nije AlertDialog alert u kodu nego smao nekreirana klasa
			 * te se preko tog parametra u ovom momentu (momentu kreiranja eventa) nemoze pristupiti konkretnom objektu dialog
			 * koji ce tek kasnije biti kreiran te je njhova zamisao ovaka
			 * unutar eventa ne obradjujes nikake podatke a ako oces da radis sa nekim objektom onda pozivas metod tog objekta
			 * u nasem slucaju CostInsert() - te taj metod radi sa podatcima objekta
			 * za razliku od Delphija ili C# dje su eventi ustvari delovi klase(tj objekta posle kreate)
			 * ovde su eventi neke metode koje ne pripadaju nikome vise u vazduhu
			 * */
		});
		alt_bld.setNegativeButton("No", new OnClickListener() {
			public void onClick(DialogInterface dialog, int id){
				dialog.cancel();
			};
		}); 
		AlertDialog alert = alt_bld.create();
		// Title for AlertDialog
		alert.setTitle("Assign type?");
		// Icon for AlertDialog
		alert.setIcon(R.drawable.help);
		//alert.show(); --necemo vise ovako - idemo na confirminsert
		ConfirmInsert(((TextView)poslati2).getText().toString());
	}
	
	private void ConfirmInsert(String code){
	try{
			Intent intent = new Intent(Intent.ACTION_VIEW);
			intent.setClassName(this, ConfirmInsert.class.getName());
			Bundle bun = new Bundle();
			bun.putString("operation", "Insert");
			bun.putString("cost_code", code);
			bun.putString("value", cost.toString());
			bun.putString("whe",util.GetCurrentDate(getApplicationContext()));
			bun.putString("description","");
			bun.putString("path", bPath.getText().toString());
			intent.putExtras(bun);
			this.startActivity(intent);
	}
	catch (Exception ex){
			Toast.makeText(this,ex.getMessage(), Toast.LENGTH_SHORT).show();}

	}

	
	
	public void CostInsert()
	{
		// Action for 'Yes' Button
		String sql = "INSERT INTO log (cost_code, value, whe) values ("+((TextView)poslati2).getText().toString()+","+cost.toString()+",date(\'now\'))";			
		util.execSQL(sql,  this);
		lv.setAdapter(null);
		Toast.makeText( this ,"Cost successfully inserted.", Toast.LENGTH_SHORT).show();
		//startActivity(new Intent(thisclass, MainActivity.class)); dont go to main, rather show what's inserted
		try{
			Intent intent = new Intent(Intent.ACTION_VIEW);
			intent.setClassName(this, CostList.class.getName());
			this.startActivity(intent);
		}catch (Exception ex){
			util.showDialog("ehm, :"+ex.getMessage().toString(), this);
		}
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
	    MenuInflater inflater = getMenuInflater();
	    inflater.inflate(R.menu.optcosttypes, menu);
	    return true;
	}
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
	    switch (item.getItemId()) {
	        case R.id.addType:
	        	contextAddIn(Level);
	        break;
	        //case R.id.costs:     
	        //	goManageCosts(thisclass);//Toast.makeText(this, "Manage Costs", Toast.LENGTH_LONG).show();
	        //    break;
	    }
	    return true;
	}
	public void onButInsertHere(View view){
	 	//Toast.makeText(this,"Not implemented, sada ce da bude!!!", Toast.LENGTH_LONG).show();
		IRefreshList ir = new IRefreshList() {
			@Override
			public void onRefreshList() {
				lv.setAdapter(null);
				fillList();//refresh
			}
		};
		DialogAddCost addDialog = new DialogAddCost(this,Level,ir);
		addDialog.show();
	}
	public void onButInsertIn(View view){
		ConfirmInsert(Level);
	}
	
	public void onButInsertWithout(View view){
		util.execSQL("INSERT INTO log (cost_code, value, whe) values (NULL,"+cost.toString()+",date(\'now\'))", this);
		Toast.makeText(this,"Cost: "+cost.toString()+" successfully inserted.", Toast.LENGTH_LONG).show();
		startActivity(new Intent(this, MainActivityTab.class));
	}
	public boolean existsChildCostttft(String parent)
	{
		Cursor c;
		util u = new util();
		c = u.getCursor("select count(*) as count from cost_type where parent = "+parent.toString(), thisclass);
		c.moveToFirst(); //count must have value
		Toast.makeText(this,"count of parents "+c.getString(0).toString(), Toast.LENGTH_LONG).show();
		String iff = c.getString(0).toString();
		c.close();
		u.db.close();
		if (iff.equals("0")){
			return false;
		}
		else{
			return true;
		}
	}
	@Override
	public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
		try{
			AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo)menuInfo;
			RelativeLayout ln = ((RelativeLayout) info.targetView);
			View vi = ln.findViewById(R.id.ctgornji);
	        selectedWord = ((TextView)vi).getText().toString();// ((TextView) info.targetView).getText().toString();
	        contextID = ((TextView)ln.findViewById(R.id.ctcode)).getText().toString();
			menu.setHeaderTitle(selectedWord);
			menu.add(0,v.getId(),0,"Move folder up");			
			menu.add(0,v.getId(),0,"Rename folder");
			menu.add(0,v.getId(),0,"Delete folder");
			menu.add(0,v.getId(),0,"Add type in here");
			
		}
		catch (Exception ex){
			Toast.makeText(this,"Error in context: "+ex.getMessage(), Toast.LENGTH_LONG).show();
		}
	}
	@Override  
	public boolean onContextItemSelected(MenuItem item) {
		String titl;
		titl = item.getTitle().toString();
	    if(titl.equals("Delete folder")){
	    	contextDelete();
	    }  
	    else if(item.getTitle().equals("Rename folder")){
	    	//function2(item.getItemId(),contextID);
			showDialog(CATEGORY_DETAIL);//ovaj prikazuje dialog a dialog preko globalnih parametara zna sta treba da radi, valjda
	    }else if (item.getTitle().equals("Add type in here")){ 
	    	contextAddIn(contextID);
	    }
	    else if (item.getTitle().equals("Move folder up")){
	    	util.moveTypeUp(Integer.parseInt(Level), contextID, thisclass);
	    	//refresh
			Intent intent = new Intent(Intent.ACTION_VIEW);
			intent.setClassName(getApplicationContext(), CostTypes.class.getName());
			Bundle bun = new Bundle();
			bun.putString("Cost",cost.toString());
			bun.putString("Level",Level);
			intent.putExtras(bun);
			startActivity(intent);
	    }else
	    	return false;  

	    
	    
	    return true;  
	}
	public void contextRename(String code, String newText){  
		util.execSQL("update cost_type set name = '"+newText+"', path='' where code ="+code, getApplicationContext());//util.getBracketValue(title), thisclass);
		lv.setAdapter(null);
		fillList();//refresh
	}

	public void contextAddIn(final String level){
		DialogAddCost da = new DialogAddCost(thisclass, level, new IRefreshList() {
			@Override
			public void onRefreshList() {
				lv.setAdapter(null);
				fillList();//refresh bojim se da je ovo nepotrebno
				//idem tamo gdje je sve po mom
				Intent intent = new Intent(Intent.ACTION_VIEW);
				intent.setClassName(getApplicationContext(), CostTypes.class.getName());
				Bundle bun = new Bundle();
				bun.putString("Cost", cost.toString());
				bun.putString("Level", level.toString());
				intent.putExtras(bun);
				startActivity(intent);

			}
		});
    	da.show();
	}

	public void contextDelete(){
		/////confirm delete
		//////////////////////////////scary alert builder dialog
		AlertDialog.Builder alt_bld = new AlertDialog.Builder(CostTypes.this);
		alt_bld.setMessage("Are you sure you want to delete this folder?");
		alt_bld.setCancelable(false);
		alt_bld.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
		public void onClick(DialogInterface dialog, int id) {
		// Action for 'Yes' Button
			try{
				String subtypes = util.getAllChildren(contextID, getApplicationContext());
				util.execSQL("delete from cost_type where code in ("+subtypes+")", getApplicationContext()); //odletise typovi
				util.execSQL("delete from log where cost_code in ("+subtypes+")", getApplicationContext()); //odletise troskovi
				
				lv.setAdapter(null);
				fillList();//refresh
			}
			catch(Exception ex)
			{
				util.showDialog(ex.getMessage(),getApplicationContext());
			}
		}
		})
		.setNegativeButton("No", new DialogInterface.OnClickListener() {
		public void onClick(DialogInterface dialog, int id) {
		//  Action for 'NO' Button
		dialog.cancel();
		}
		});
		AlertDialog alert = alt_bld.create();
		// Title for AlertDialog
		alert.setTitle("Delete cost?");
		// Icon for AlertDialog
		alert.setIcon(R.drawable.help);
		alert.show();
		//////////////////////////////end scary alert builder dialog
		/////confirm delete
	}
    public void function2(int id, String title){  
        //Toast.makeText(this, "function 2 called"+title, Toast.LENGTH_SHORT).show();  
    }
    @Override
    protected Dialog onCreateDialog(int id) {
        switch (id) {
            case CATEGORY_DETAIL:
                LayoutInflater li = LayoutInflater.from(this);
                View categoryDetailView = li.inflate(R.layout.dialog_editview, null);
                
                AlertDialog.Builder categoryDetailBuilder = new AlertDialog.Builder(this);
                categoryDetailBuilder.setTitle("Edit Category");
                categoryDetailBuilder.setView(categoryDetailView);
                AlertDialog categoryDetail = categoryDetailBuilder.create();
                
                categoryDetail.setButton("OK", new OnClickListener(){
                
	                @Override
	                public void onClick(DialogInterface dialog, int which) {
	                    AlertDialog categoryDetail = (AlertDialog)dialog;
	                    EditText et = (EditText)categoryDetail.findViewById(R.id.categoryEditText);
	                    if ("1"!=null){
	                        //... some code
	                    	Toast.makeText(getApplicationContext(),"Costtypes: testing "+et.getText().toString(), Toast.LENGTH_LONG).show();
	                    	contextRename(contextID, et.getText().toString());
	                    }               
	                }
	            });
                
                categoryDetail.setButton2("Cancel", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    return;
                }}); 
                
                return categoryDetail;
            default:
                break;
        }
        return null;
    }
    
    
    
    @Override
    protected void onPrepareDialog(int id, Dialog dialog) {
        switch (id) {
            case CATEGORY_DETAIL:
                AlertDialog categoryDetail = (AlertDialog)dialog;
                EditText et = (EditText)categoryDetail.findViewById(R.id.categoryEditText);
                et.setText(selectedWord);
                break;
            default:
                break;
        }
    }
}
